package com.hpin.fansea.service;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.LoadPicResult;
import com.hpin.fansea.choosepic.MyAdapter;
import com.hpin.fansea.home.ChoosePhotoActivity;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.widget.ActionSheetDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * 出租发布页面
 * Created by Aaron on 15/9/16.
 */
public class RentReleaseActivity extends BaseActivity {

    private ImageView iv_first;
    private ImageView iv_second;
    private ImageView iv_third;
    private ImageView iv_four;

    private List<String> picUrls = new ArrayList<String>();// 存放用户上传的图片的地址

    private ExecutorService executor;

    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 10025;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 10026;

    /*拍照的文件保存的位置*/
    private File currentFile;
    private ArrayList<String> tempTakeLists;
    private EditText et_title;
    private EditText et_sale_price;
    private EditText et_describe;
    private TextView tv_address;
    private EditText et_contact;
    private EditText et_contact_tel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_houseinfo_release);

        tempTakeLists = new ArrayList<String>();

        initWidget();

        setUserData();
    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.rent_release));

        iv_left.setOnClickListener(this);

        tv_address = (TextView) findViewById(R.id.tv_address);
        et_title = (EditText) findViewById(R.id.et_title);
        et_sale_price = (EditText) findViewById(R.id.et_sale_price);
        et_describe = (EditText) findViewById(R.id.repair_reason);
        et_contact = (EditText) findViewById(R.id.et_contact);
        et_contact_tel = (EditText) findViewById(R.id.et_contact_tel);

        TextView tv_style = (TextView) findViewById(R.id.tv_style);
        tv_style.setText(getResources().getString(R.string.rent_price));

        Button btn_release = (Button) findViewById(R.id.btn_release);

        iv_first = (ImageView) findViewById(R.id.iv_first);
        iv_second = (ImageView) findViewById(R.id.iv_second);
        iv_third = (ImageView) findViewById(R.id.iv_third);
        iv_four = (ImageView) findViewById(R.id.iv_four);

        iv_first.setOnClickListener(this);
        iv_second.setOnClickListener(this);
        iv_third.setOnClickListener(this);
        iv_four.setOnClickListener(this);

        btn_release.setOnClickListener(this);

        setClickableFalse(iv_second);
        setClickableFalse(iv_third);
        setClickableFalse(iv_four);

    }

    /**
     * 设置用户的基本数据
     */
    private void setUserData() {

        tv_address.setText(sp.getString(Constant.communityId, "") + "期" + sp.getString(Constant.buildingNo, "")
                + sp.getString(Constant.unitNo, "") + sp.getString(Constant.houseNo, ""));

        et_contact.setText(sp.getString(Constant.userName, ""));

        et_contact_tel.setText(sp.getString(Constant.mobile, ""));

//        if (!CommonUtils.isNull(et_contact.getText().toString().trim()))
//            et_contact.setSelection(et_contact.getText().toString().trim().length());
//
//        if (!CommonUtils.isNull(et_contact_tel.getText().toString().trim()))
//            et_contact_tel.setSelection(et_contact_tel.getText().toString().trim().length());

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;

            case R.id.iv_first:
            case R.id.iv_second:
            case R.id.iv_third:
            case R.id.iv_four:

                showChoose();

                break;

            case R.id.btn_release://发布

                checkRelease();

                break;

        }

    }

    /**
     * 发布
     */
    private void checkRelease() {

        if (CommonUtils.isNull(et_title.getText().toString().trim())) {
            showToast("标题不能为空");
            return;
        }

        if (et_title.getText().toString().trim().length()<2 || et_title.getText().toString().trim().length()>20) {
            showToast("标题应为2-20字");
            return;
        }

        if (CommonUtils.isNull(et_sale_price.getText().toString().trim())) {
            showToast("价格不能为空");
            return;
        }

        if (CommonUtils.isNull(et_describe.getText().toString().trim())) {
            showToast("描述内容不能为空");
            return;
        }

        if (et_describe.getText().toString().trim().length()<10 || et_describe.getText().toString().trim().length()>200) {
            showToast("描述应为10-200字");
            return;
        }

        if (CommonUtils.isNull(et_contact.getText().toString().trim())) {
            showToast("联系人不能为空");
            return;
        }

        if (CommonUtils.isNull(et_contact_tel.getText().toString().trim())) {
            showToast("联系电话不能为空");
            return;
        }

        if (!CommonUtils.isPhone(et_contact_tel.getText().toString().trim())) {
            showToast("请输入正确的手机号码");
            return;
        }

        release();


    }

    /**
     * 发布
     */
    private void release() {



    }

    /**
     * 弹出选择照片的对话框
     */
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }

    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        Intent intent = new Intent(this, ChoosePhotoActivity.class);
        startActivityForResult(intent, PHOTO_ALBUM_CODE);

    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + Constant.PHOTO_CACHE;
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PHOTO_ALBUM_CODE) {//从相册中选择

            if (data == null)
                return;

            ArrayList<String> selectPics = data.getStringArrayListExtra("selectedPhotos");

            tempTakeLists.addAll(selectPics);

            //逐张上传图片
            for (String pic : selectPics) {

                loadPicToNet(pic);

            }

            setImage(selectPics);

        } else if (requestCode == TAKE_PHOTO_CODE) {

            //上传图片
            if (currentFile != null && currentFile.exists()) {

                loadPicToNet(currentFile.getPath());

            }

            tempTakeLists.add(currentFile.getPath());
            setImage(tempTakeLists);

        }

    }

    private void setImage(List<String> selectPics) {

        switch (selectPics.size()) {

            case 1:

                setClickableFalse(iv_first);
                setClickableTrue(iv_second);

                setClickableFalse(iv_third);
                setClickableFalse(iv_four);
                iv_second.setImageResource(R.mipmap.icon_choose_pic);

                iv_third.setImageResource(R.mipmap.icon_wait_choose);
                iv_four.setImageResource(R.mipmap.icon_wait_choose);

                iv_first.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(0)));

                break;
            case 2:

                setClickableFalse(iv_first);
                setClickableFalse(iv_second);
                setClickableTrue(iv_third);

                setClickableFalse(iv_four);
                iv_third.setImageResource(R.mipmap.icon_choose_pic);

                iv_four.setImageResource(R.mipmap.icon_wait_choose);

                iv_first.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(0)));
                iv_second.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(1)));

                break;
            case 3:

                setClickableFalse(iv_first);
                setClickableFalse(iv_second);
                setClickableFalse(iv_third);
                setClickableTrue(iv_four);
                iv_four.setImageResource(R.mipmap.icon_choose_pic);

                iv_first.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(0)));
                iv_second.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(1)));
                iv_third.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(2)));

                break;
            case 4:

                setClickableFalse(iv_first);
                setClickableFalse(iv_second);
                setClickableFalse(iv_third);
                setClickableFalse(iv_four);

                iv_first.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(0)));
                iv_second.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(1)));
                iv_four.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(3)));

                break;

        }

    }


    /**
     * 让控件不可点击
     *
     * @param iv
     */
    private void setClickableFalse(ImageView iv) {

        iv.setClickable(false);
        iv.setFocusable(false);
        iv.setEnabled(false);

    }

    /**
     * 让控件可点击
     *
     * @param iv
     */
    private void setClickableTrue(ImageView iv) {

        iv.setClickable(true);
        iv.setFocusable(true);
        iv.setEnabled(true);

    }

    /**
     * 上传图片
     *
     * @param picturePath 该图片在手机上的地址
     */
    private void loadPicToNet(String picturePath) {

        if (executor == null)
            executor = Executors.newSingleThreadExecutor();

        executor.execute(loadToNet(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(picturePath))));

    }

    /**
     * 上传图片的runnable
     *
     * @param bytes 图片的字节数组
     * @return
     */
    private Runnable loadToNet(final byte[] bytes) {

        return new Thread() {
            @Override
            public void run() {

                String upResult = HttpUtil.getInstance().load(Constant.WEB_ROOT + Constant.UPLOADPIC + "/" + sp.getString(Constant.token, ""), bytes);

                try {

                    LoadPicResult loadPicResult = JSONObject.parseObject(upResult, LoadPicResult.class);

                    if (Constant.STATUS_SUCESS.equals(loadPicResult.status)) {

                        //上传成功,保存到上传的集合中
                        picUrls.add(loadPicResult.result);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //删除集合中的图片
        MyAdapter.mSelectedImage.clear();

    }
}
